package com.rongji.dfish.demo.login.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rongji.dfish.base.Utils;
import com.rongji.dfish.demo.entity.PubLoginUser;
import com.rongji.dfish.demo.index.view.DemoView;
import com.rongji.dfish.demo.login.view.LoginView;
import com.rongji.dfish.demo.pub.service.UserService;
import com.rongji.dfish.demo.pub.view.PubView;
import com.rongji.dfish.framework.FrameworkHelper;
import com.rongji.dfish.framework.IdGenerator;
import com.rongji.dfish.framework.controller.BaseController;
import com.rongji.dfish.ui.Widget;
import com.rongji.dfish.ui.command.CommandGroup;
import com.rongji.dfish.ui.command.DialogCommand;
import com.rongji.dfish.ui.command.JSCommand;
import com.rongji.dfish.ui.command.ReplaceCommand;
import com.rongji.dfish.ui.command.TipCommand;
import com.rongji.dfish.ui.layout.VerticalLayout;

@Controller
@RequestMapping("/login")
public class LoginController extends BaseController {
	@Autowired
	private UserService userService;
	
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}	
	@RequestMapping(value = "/toLogin")
	@ResponseBody
	public Object toLogin(HttpServletRequest request) throws Exception {
		DialogCommand dialog = PubView.getDialogCommand("toLogin", "std", null, PubView.DIALOG_SIZE_LARGE, null).setWidth(DialogCommand.WIDTH_SMALL).setCover(true);
		dialog.setNode(LoginView.buildLoginView());
		return dialog;
	}
	@RequestMapping(value = "/doLogin")
	@ResponseBody
	public Object login(HttpServletRequest request) throws Exception {
		
 		String loginName = request.getParameter("loginName");
		String password = request.getParameter("password");
		if(Utils.isEmpty(loginName)){
			String loginUserKey=FrameworkHelper.getLoginUser(request);
			if(Utils.notEmpty(loginUserKey)){
				CommandGroup cg = new CommandGroup();
				cg.setPath("/");
				PubLoginUser loginUser = userService.get(loginUserKey);
				ReplaceCommand uc = new ReplaceCommand();
				cg.add(uc);
				Widget<?> loginBar = DemoView.buildLoginBar(loginUser);
				uc.setNode(loginBar);
				return cg;
			}else{
				return new JSCommand("");
			}
		}
		
		CommandGroup cg = new CommandGroup();
		PubLoginUser loginUser = userService.getUserByLoginName(loginName);
		if (loginUser!=null) {
			if(password.equals(loginUser.getUserPwd())){
				Date now = new Date(System.currentTimeMillis());
				//记录登录时间
				loginUser.setLastLoginTime(now);
				userService.update(loginUser);
				
				FrameworkHelper.setLoginUser(request, loginUser.getUserId());
				
				cg=getReloadCommand(loginUser);
				
			}else{
				cg.add( new TipCommand("密码错误！").setSnap("password").setSnaptype("tb"));
			}
		} else {
			cg.add( new TipCommand("您输入的账号不存在！").setSnap("loginName").setSnaptype("tb"));
		}
		return cg;
	}
	@RequestMapping(value = "/toReg")
	@ResponseBody
	public Object toReg(HttpServletRequest request) throws Exception {
		VerticalLayout main=LoginView.buildToRegView(480);
		return new ReplaceCommand().setNode(main);
	}
	@RequestMapping(value = "/changeToLogin")
	@ResponseBody
	public Object changeToLogin(HttpServletRequest request) throws Exception {
		VerticalLayout main=(VerticalLayout) LoginView.buildLoginView().findNodeById("main");
		return new ReplaceCommand().setNode(main);
	}
	
	@RequestMapping(value = "/doReg")
	@ResponseBody
	public Object doReg(HttpServletRequest request) throws Exception {
		String loginName = Utils.getParameter(request,"loginName");
		String password = request.getParameter("password");
		
		//先判断用户名是否存在，若存在弹出提示
		//不存在，进行注册
		PubLoginUser loginUser = userService.getUserByLoginName(loginName);
		if(loginUser!=null){
			return new TipCommand("该用户名已存在！").setSnap("loginName").setSnaptype("tb");
		}else{
			PubLoginUser regUser=new PubLoginUser();
			regUser.setUserId(IdGenerator.getSortedId());
			regUser.setUserPwd(password);
			bind(request,regUser);
			userService.save(regUser);
			CommandGroup cg=new CommandGroup();
			cg.add(PubView.getAjaxCommand("login/changeToLogin"));
//			cg.add(new JSCommand("dfish.alert('注册成功，请前往登录！');"));
			cg.add(PubView.getAlertInfo("注册成功!"));
			return cg;
		}
	}
	
	@RequestMapping(value = "/logout")
	@ResponseBody
	public Object logout(HttpServletRequest request) throws Exception {
		FrameworkHelper.removeLoginUser(request);
		CommandGroup cg = getReloadCommand(null);
		return cg;
	}
	@RequestMapping(value = "/showAgree")
	@ResponseBody
	public Object showAgree(HttpServletRequest request) throws Exception {
		DialogCommand dialog = new DialogCommand("showAgree", "std", "DFish开发框架使用协议",  DialogCommand.WIDTH_LARGE, DialogCommand.HEIGHT_LARGE, null, "");
		dialog.setNode(LoginView.buildAgreeView());
		return dialog;
	}
	/**
	 * 登录或者退出之后，根据用户状态刷新loginBar以及相对应的编辑面板
	 * @param loginUser
	 * @return
	 */
	private CommandGroup getReloadCommand(PubLoginUser loginUser){
		CommandGroup cg = new CommandGroup();
		cg.setPath("/index");
		ReplaceCommand uc = new ReplaceCommand();
		cg.add(uc);
		Widget<?> loginBar = DemoView.buildLoginBar(loginUser);
		uc.setNode(loginBar);
		cg.add(new JSCommand("dfish.close('toLogin');"));
		cg.add(new JSCommand("var vm=dfish.vm(this);" +
				"var tabBar=vm.find('wstab');" +
				"var mod='';" +
				"for(var i=1 ;i<tabBar.length;i++){" +
					"if(tabBar[i].x.focus==true){" +
					" mod=tabBar[i].x.target;break;" +
					"}" +
				"}" +
				"if(mod){vm.find(mod).reload();}"));
		return cg;
	}
	
}
